import { ITypeState } from '@/models/typeModel';
import BookController from '@/services/book';
import { IBook } from '@/types/book';
import { formatDate } from '@/utils/tools';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Card, Col, Image, Popover, Row, Statistic, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useDispatch, useSelector } from 'umi';

const BookDetail: React.FC = () => {
  const { bookId } = useParams(); // 获取可能传递过来的 id
  const [bookInfo, setBookInfo] = useState<IBook>();
  const [typeName, setTypeName] = useState<string>();
  const dispatch = useDispatch(); // 获取 dispatch

  // 从仓库获取类型列表
  const { typeList }: ITypeState = useSelector((state: any) => state.type);

  useEffect(() => {
    // 如果类型列表为空，则初始化一次
    if (!typeList.length) {
      dispatch({
        type: 'type/_initTypeList',
      });
    }

    // 根据传递过来的 id 获取面试题详情
    async function fetchData() {
      // 根据问答 id 获取该问答具体的信息
      if (!bookId) return;
      const { data } = await BookController.getBookById(bookId);
      setBookInfo(data);
      console.log(data);

      // 获取 typeId 对应的 typeName
      const type = typeList.find((item) => item._id === data.typeId);
      setTypeName(type?.typeName);
    }
    fetchData();
  }, []);

  const content = (
    <div style={{ maxWidth: '300px', wordBreak: 'break-all' }}>
      <p>下载链接：{bookInfo?.downloadLink}</p>
      <p>所需积分：{bookInfo?.requirePoints}</p>
    </div>
  );
  return (
    <PageContainer>
      <Card
        title={bookInfo?.bookTitle}
        style={{
          marginBottom: 10,
        }}
        extra={
          <>
            <Popover content={content} title="下载信息">
              <Button type="link">下载信息</Button>
            </Popover>
            <Tag color="purple" key={bookInfo?.typeId}>
              {typeName}
            </Tag>
          </>
        }
      >
        <Row>
          <Col span={8}>
            <Image height={350} src={bookInfo?.bookPic} />
            <Row gutter={16} style={{ margin: '20px' }}>
              <Col span={12}>
                <Statistic title="浏览数" value={bookInfo?.scanNumber} />
              </Col>
              <Col span={12}>
                <Statistic title="评论数" value={bookInfo?.commentNumber} />
              </Col>
            </Row>
            <h3>上架时间：{formatDate(bookInfo?.onShelfDate)}</h3>
          </Col>
          <Col span={16}>
            <div
              dangerouslySetInnerHTML={{
                __html: bookInfo?.bookIntro ? bookInfo?.bookIntro : '',
              }}
            ></div>
          </Col>
        </Row>
      </Card>
    </PageContainer>
  );
};

export default BookDetail;
